package vulnapp.service;

import org.springframework.stereotype.Service;
import vulnapp.dto.LocationDto;
import vulnapp.entity.Location;
import vulnapp.repository.LocationRepository;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Service
public class LocationServiceImpl implements LocationService {

    private final LocationRepository LocationRepository;

    public LocationServiceImpl(LocationRepository LocationRepository) {
        this.LocationRepository = LocationRepository;
    }

    @Override
    public void saveLocation(LocationDto locationDto) {
        Location location = new Location();
        location.setCode(locationDto.getCode());
        location.setCoordinates(locationDto.getCoordinates());
        LocationRepository.save(location);
    }

    @Override
    public Location findLocationByCode(String code) {
        return LocationRepository.findByCode(code);
    }

    public List<LocationDto> unsafeFindLocation(String code, DataSource dataSource) {

        String sql = "select " + "* from location where code = '" + code + "'";
        System.out.println(sql);

        try (Connection c = dataSource.getConnection();
             ResultSet rs = c.createStatement()
                     .executeQuery(sql)) {
            List<LocationDto> locations = new ArrayList<>();
            while (rs.next()) {
                LocationDto loc = new LocationDto();
                loc.setCode(rs.getString("code"));
                loc.setCoordinates(rs.getString("coordinates"));
                locations.add(loc);
            }

            return locations;
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }
    }

    @Override
    public Location findLocationByCoordinates(String coordinates) {
        return LocationRepository.findByCoordinates(coordinates);
    }

}
